use std::fs::create_dir_all;

use model_graph_common::utils::{new_uuid, rrg01_home_path, write_to_file, zip::compress_dir};
use model_graph_types::{
    database::{ConnectorProtocol, DataSource, DatabaseType},
    transform::{DomainTransformerOptions, DomainTransformerUnit},
};

/// 领域数据转移
pub async fn export_domain_to_file(
    source: &DataSource,
    target: &String,
    domains: &DomainTransformerUnit,
    options: &DomainTransformerOptions,
) -> anyhow::Result<()> {
    //获取程序目录
    let home_path = format!(
        "{}",
        rrg01_home_path()
            .map_err(|err| anyhow::anyhow!("获取程序目录失败:{}", err))?
            .to_str()
            .map_or(Err(anyhow::anyhow!("获取程序目录失败")), |v| Ok(v))?
    );
    //创建导出的临时目录
    let export_path = format!("{}/temp/{}/", home_path, new_uuid()?);
    let _ = create_dir_all(&export_path);
    let target_sqlite_file = format!("{}/domain.sqlite", &export_path);

    //创建导出的sqlite数据文件
    let _ = write_to_file(export_path.as_str(), "domain.sqlite", &vec![]);

    let target_datasource = DataSource {
        database_type: DatabaseType::SQLite,
        protocol: ConnectorProtocol::SQLite,
        url: target_sqlite_file.clone(),
        ..Default::default()
    };

    super::domain_transform(source, &target_datasource, domains, options).await?;

    //涉及到的一些文件进行拷贝
    //1. 特性流程文件

    //压缩目录
    compress_dir(export_path.as_str(), target.as_str())?;

    Ok(())
}
